package com.syz.mall.controller;

import com.syz.mall.pojo.Cart;
import com.syz.mall.pojo.User;
import com.syz.mall.pojo.vo.CartVO;
import com.syz.mall.service.ICartService;
import com.syz.mall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private ICartService cartService;

    @RequestMapping("/add")
    @ResponseBody
    public Result add(Cart cart, HttpSession session) {
        System.out.println("CartController.add");
        User user = (User) session.getAttribute("user");
        cart.setUserId(user.getId());
        boolean isSuccess = cartService.add(cart);
        return isSuccess ? Result.ok("加入购物车成功") : Result.error("加入购物车失败，可能库存不足");
    }

    @RequestMapping("/getCartListPage")
    public String getCartListPage(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<CartVO> list = cartService.selectByUserId(user.getId());
        model.addAttribute("list", list);
        return "shop_cart";
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public Result deleteById(Integer id) {
        //System.out.println("CartController.deleteById");
        boolean isSuccess = cartService.deleteById(id);
        return isSuccess ? Result.ok("删除成功") : Result.error("删除购物车失败");
    }

    @RequestMapping("/updateChecked")
    @ResponseBody
    public Result updateChecked(Integer id, Integer checked) {
        System.out.println("CartController.updateChecked");
        boolean isSuccess = cartService.updateChecked(id, checked);
        return isSuccess ? Result.ok("更新成功") : Result.error("更新失败");
    }
    @RequestMapping("/changeCartSelective")
    @ResponseBody
    public Result changeQuantity(Cart cart) {
        boolean isSuccess = cartService.updateByPrimaryKeySelective(cart);
        return isSuccess ? Result.ok("更新成功") : Result.error("更新失败");
    }

    @RequestMapping("/queryCount")
    @ResponseBody
    public Map<String, Integer> queryCount(HttpSession session){
        User user = (User) session.getAttribute("user");
        Map<String, Integer> map=new HashMap<>();
        int count=cartService.selectCountByUserId(user.getId());
        map.put("num",count);
        return map;
    }
}
